package com.zretc.controller;

import com.util.CodeMsg;
import com.util.Result;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Filename:    ValidateHandler
 * Description: 验证，参数绑定异常统一处理
 * Copyright:   Copyright (c) 2018-2019 All Rights Reserved.
 * Company:     chinasofti.com Inc.
 *
 * @author: mazheng
 * @version: 1.0
 * Create at:   2022-08-22
 * <p>
 * Modification History:
 * Date         Author      Version     Description        tag
 * ------------------------------------------------------------------
 * 2022-08-22      mazheng      1.0         1.0 Version        new
 */
@RestControllerAdvice
public class ValidateHandler {
//    @ResponseStatus(HttpStatus.BAD_REQUEST)

    /**
     * 验证异常处理
     * @param e     参数错误信息
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler1(BindException e){

        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();

        return Result.error(objectError.getDefaultMessage());
    }

    /**
     * 入参异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public Result handler2(BindException e){

        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();

        return Result.error(objectError.getDefaultMessage());
    }
}
